/**
 * Universita' degli Studi di Palermo, 2010-11
 */
package org.aitools.programd.server.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.Principal;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.aitools.programd.Core;
import org.aitools.programd.bot.Bot;
import org.aitools.programd.bot.Bots;

/**
 * @author Giuseppe Miceli
 *
 */
public class SimpleServlet extends HttpServlet{

	// TODO Commentare e sistemare la classe
	/**
	 * 
	 */
	private static final long serialVersionUID = -6523168370991893684L;
	protected Core core;

	@Override
	public void init() {
		this.core = (Core)getServletContext().getAttribute("core");
	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		setupBot(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		setupBot(req, resp);
	}

	protected void setupBot(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// Get/create the session.
		HttpSession session = req.getSession(true);

		PrintWriter out = resp.getWriter();

		String phrase = req.getParameter("phrase");

		// Look for a userid.
		String userid = null;

		userid = req.getParameter("userid");
		if (userid == null){
			Principal principal = req.getUserPrincipal();
			if (principal == null)	{
				userid = session.getId();
			} else {
				userid = principal.getName();
			}
		}
		if (userid == null)	{
			req.setAttribute("error", "Could not figure out a usable userid.");
			return;
		}

		// Get the bot parameter, if there is one.
		String botid = req.getParameter("botid");

		// It might be in a request attribute.
		if (botid == null)
		{
			botid = (String)req.getAttribute("botid");
		}

		// We intend to wind up with some sort of Program D Bot object, one way or another.
		Bot programDBot = null;	

		if (this.core != null)
		{
			Bots bots = this.core.getBots();
			if (bots != null && bots.getCount() > 0)
			{
				if (botid != null && this.core.getBots().include(botid)){
					programDBot = this.core.getBot(botid);
				} else {
					programDBot = this.core.getBots().getABot();
				}
			}
		} else return;

		// TODO definire un protocollo per i risultati
		String result = core.getResponse(phrase, userid, programDBot.getID());

		out.println(result);
		out.flush();
		out.close();
	}
}
